<?php

/**
 * WSB_PageRenderer
 *
 * PHP version 5
 *
 * @copyright  2007 Zephir Software Design AG
 */
class WSB_PageRenderer
{

	/**
	 * @var Cms_Model_Page
	 */
    private $_page;

    /**
     * @var Cms_Model_Template
     */
    private $_template;

    /**
     * @var Cms_Model_Language
     */
    private $_language;

    /**
     * @var Zend_Session_Namespace
     */
    private $_session;

    /**
     * @var array
     */
    private $_contentPerPlaceholder;

    /**
     * @var array
     */
    private $_hasContent;


    /**
     * @param Cms_Model_Page $page
     * @param Cms_Model_Template $template
     * @param Cms_Model_Language $language
     */
    public function __construct(Cms_Model_Page $page, Cms_Model_Template $template, Cms_Model_Language $language)
	{
        $this->_page = $page;
        $this->_template = $template;
        $this->_language = $language;
        $this->_session = null;
        $this->_contentPerPlaceholder = array();
        $this->_hasContent = array();
    }

    /**
     * @return boolean
     */
    private function _editorIsOn()
	{
		return isset($this->_session->editorIsOn) && $this->_session->editorIsOn;
    }

    /**
     * @return boolean
     */
    private function _editorIsOff()
	{
    	return !$this->_editorIsOn;
    }

    /**
     * @return boolean
     */
    private function _authHasIdentity()
	{
		return WSB_Auth_Backend::getInstance()->hasIdentity();
    }

    /**
     * @param string $html
     * @return string
     */
    private function showInvisibles($html)
	{
    	$replacements = array(
    		'<br />'	=> '<font style="color:#aaa;">&crarr;</font><br />',
    		'</p>'		=> '<font style="color:#aaa;">&para;</font></p>',
    		'</h1>'		=> '<font style="color:#aaa;"> h1</font></h1>',
    		'</h2>'		=> '<font style="color:#aaa;"> h2</font></h2>',
    		'</h3>'		=> '<font style="color:#aaa;"> h3</font></h3>',
    		'</h4>'		=> '<font style="color:#aaa;"> h4</font></h4>',
    		'</h5>'		=> '<font style="color:#aaa;"> h5</font></h5>',
    		'</h6>'		=> '<font style="color:#aaa;"> h6</font></h6>',
    		'</li>'		=> '<font style="color:#aaa;">&para;</font></li>'
    	);
	   	return str_ireplace(array_keys($replacements), array_values($replacements), $html);
    }

    /**
     * Rendere den Seiteninhalt.
     *
     * @param Zend_View_Interface $view
     */
    public function render(Zend_View_Interface $view)
	{

		// Beuser ist eingeloggt
		if($this->_authHasIdentity()) {
			$this->_session = new Zend_Session_Namespace(get_class($this));

			// Editor ein-/ausschalten
			if(isset($_GET['editor'])) {
				if($_GET['editor'] == 'on') {
					$this->_session->editorIsOn = true;
				}
				if($_GET['editor'] == 'off') {
					$this->_session->editorIsOn = false;
				}
			}
			// Editor Default-Einstellung
			if(is_null($this->_session->editorIsOn)) {
				$this->_session->editorIsOn = true;
			}

			// Invisibles ein-/ausschalten
			if(isset($_GET['invisibles'])) {
				if($_GET['invisibles'] == 'on') {
					$this->_session->invisibles = true;
				}
				if($_GET['invisibles'] == 'off') {
					$this->_session->invisibles = false;
				}
			}
			// Invisibles Default-Einstellung
			if(is_null($this->_session->invisibles)) {
				$this->_session->invisibles = false;
			}

			$links = array();
			//array_push($links, WSB_Controller_Url::getHtmlPopupLink('Sitemap', Cms_Url::pageOverviewUrl(true), 500, 500));

			// Invisibles-Link
			$linkVars = $_GET;
        	if($this->_session->invisibles) {
        		$linkVars['invisibles'] = 'off';
				array_push($links, sprintf('<a href="%s">Invisibles off</a>', $view->urlThisPage($linkVars)));
        	} else {
        		$linkVars['invisibles'] = 'on';
				array_push($links, sprintf('<a href="%s">Invisibles on</a>', $view->urlThisPage($linkVars)));
        	}

			// Editor-Link
			$linkVars = $_GET;
        	if($this->_editorIsOn()) {
        		$linkVars['editor'] = 'off';
				array_push($links, sprintf('<a href="%s">Editor off</a>', $view->urlThisPage($linkVars)));
        	} else {
        		$linkVars['editor'] = 'on';
				array_push($links, sprintf('<a href="%s">Editor on</a>', $view->urlThisPage($linkVars)));
        	}

        	// Editor Links
	        $view->editorSwitcher = sprintf('<div class="wsb-editpanel"><div class="wsb-editpanel-links"><div>%s</div></div></div>', implode('<span class="delim">|</span>', $links));

	        // Frontend CSS
	        $frontendCss = 'design/css/frontend.css';
	        if(is_readable($frontendCss)) {
				$relCssPath = $frontendCss;
	        } else {
				$relCssPath = 'WSB/design/default/skin/default/css/frontend.css';
	        }
	        $view->headLink()->appendStylesheet($relCssPath);
		}

		$includeHiddens = false;
		// Beuser eingeloggt, Editor eingeschaltet
		if($this->_editorIsOn() && $this->_authHasIdentity()) {
			$includeHiddens = true;
		}

		// Platzhalter
		$table = new Cms_Model_DbTable_Placeholder();
		$select = $table->select();
		$select->where('hidden=?', 0);
		$select->where('deleted=?', 0);
		$placeholders = $table->fetchAll($select);

		$feUser = WSB_Auth_Frontend::getInstance()->getIdentity();

		// Container der Eltern Seite
		$containers = $this->_page->getParentPageContainers($includeHiddens);
		foreach($containers->getPlaceholderIds($this->_language->id) AS $placeholder_id) {
		    $pContainers = $containers->getContainers($this->_language->id, $placeholder_id);
		    foreach($pContainers AS $container) {
		    	// Zugriff fuer Benutzer pruefen
		    	if($container->hasAccess($feUser) || ($this->_editorIsOn() && $this->_authHasIdentity())) {
					$XT = $container->getXtInstance();
	                if($XT instanceof WSB_Xtension_Base) {
						// Stylesheet einbinden
						$stylesheet = $XT->getStylesheet();
						if(!empty($stylesheet)) {
							$view->headStyle()->offsetSetStyle($XT->getModuleName(), $stylesheet);
						}

						// Javascript einbinden
						$javascript = $XT->getJavascript();
						if(!empty($javascript)) {
							$view->headScript()->offsetSetScript($XT->getModuleName(), $javascript);
						}

						// Beuser eingeloggt, Editor eingeschaltet
	    	            if($this->_editorIsOn() && $this->_authHasIdentity() && $placeholders->isEditable($placeholder_id)) {
	    	            	$wrap = '<div class="wsb-editpanel-recursive">%s</div>';
							$this->_contentPerPlaceholder[$placeholder_id][] = sprintf($wrap, $XT->render());
						} else {
							$this->_contentPerPlaceholder[$placeholder_id][] = $XT->render();
						}
	                }
		   		}
		    }
		}

		// Container der aktuellen Seite (inkl. rekursiv markierte Container)
		$pContainerSet = $this->_page->getContainers($includeHiddens);
		foreach($pContainerSet->getPlaceholderIds($this->_language->id) AS $placeholder_id) {
		    $pContainers = $pContainerSet->getContainers($this->_language->id, $placeholder_id);
            $panel = new WSB_Panel();
			$panel->setContainerCount(count($pContainers));
		    foreach($pContainers AS $container) {
		    	// Zugriff fuer Benutzer pruefen
		    	if($container->hasAccess($feUser) || ($this->_editorIsOn() && $this->_authHasIdentity())) {
					$XT = $container->getXtInstance();
	                if($XT instanceof WSB_Xtension_Base) {
						// Stylesheet einbinden
						$stylesheet = $XT->getStylesheet();
						if(!empty($stylesheet)) {
							$view->headStyle()->offsetSetStyle($XT->getModuleName(), $stylesheet);
						}

						// Javascript einbinden
						$javascript = $XT->getJavascript();
						if(!empty($javascript)) {
							$view->headScript()->offsetSetScript($XT->getModuleName(), $javascript);
						}

						$content = (isset($this->_session->invisibles) && $this->_session->invisibles) ? $this->showInvisibles($XT->render()) : $XT->render();

						// Beuser eingeloggt, Editor eingeschaltet
	    	            if($this->_editorIsOn() && $this->_authHasIdentity() && $placeholders->isEditable($placeholder_id)) {
	    	            	if(empty($container->recursive)) {
	    	            		$wrap = '<div class="wsb-editpanel">%s%s</div>';
	    	            	} else {
	    	            		$wrap = '<div class="wsb-editpanel-recursive">%s%s</div>';
	    	            	}
							$this->_contentPerPlaceholder[$placeholder_id][] = sprintf($wrap, $content, $panel->buildFrontendPanel($container, $XT));
						} else {
							$this->_contentPerPlaceholder[$placeholder_id][] = $content;
						}
						$this->_hasContent[$placeholder_id] = true;
	                }
		   		}
		    }
		}

		$html = $this->_template->getHtmlFromNestedTemplates($view);

		// Durch alle Platzhalter gehen
		$placeholderIds = array();
		preg_match_all('#{{([0-9]+)}}#ie', $html, $placeholderIds);
		$from	= array();
		$to		= array();
		if(array_key_exists(1, $placeholderIds) && (count($placeholderIds[1]) > 0)) {
        	$translate = Zend_Registry::get('Zend_Translate');
			foreach($placeholderIds[1] AS $id) {

				$replacement = '';
				if(array_key_exists($id, $this->_contentPerPlaceholder)) {
					$replacement .= implode('', $this->_contentPerPlaceholder[$id]);
				}

				// Es gibt KEINE nichtrekursive (=normale) Container
				// Platzhalter ist editierbar
				if($this->_editorIsOn() && $this->_authHasIdentity() && $placeholders->isEditable($id)) {
					if(empty($replacement) && empty($this->_hasContent[$id])) {
						$url = Cms_Url::containerSelectModuleUrl($this->_page->id, $id, 0, $this->_language->id, true);
	                	$replacement .= '<div class="wsb-editpanel"><div class="wsb-editpanel-links"><div>' . WSB_Controller_Url::getHtmlPopupLink($translate->_('add'), $url) . '</div></div></div>';
					}
				}

				$from[] = sprintf('{{%s}}', $id);
				$to[]	= $replacement;

			}
		}

		$view->content = str_replace($from, $to, $html);
	}

}
